package avicit.bdp.dds.common.utils;

import avicit.bdp.core.util.json.JSONUtils;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.Lookup;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.SPNegoSchemeFactory;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import java.io.IOException;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


/**
 * TODO  暂时不用， kerberos有问题
 *
 * @author xugb
 * @date 2021/9/6 14:19
 */
public class HttpKerberosUtils {
    public static Logger logger = LoggerFactory.getLogger(HttpKerberosUtils.class);
    private String principal;
    private String keyTabLocation;

    public HttpKerberosUtils() {
    }

    public HttpKerberosUtils(String principal, String keyTabLocation) {
        super();
        this.principal = principal;
        this.keyTabLocation = keyTabLocation;
    }

    public HttpKerberosUtils(String principal, String keyTabLocation, boolean isDebug) {
        this(principal, keyTabLocation);
        if (isDebug) {
            System.setProperty("sun.security.spnego.debug", "true");
            System.setProperty("sun.security.krb5.debug", "true");
        }
    }

    public HttpKerberosUtils(String principal, String keyTabLocation, String krb5Location, boolean isDebug) {
        this(principal, keyTabLocation, isDebug);
        System.setProperty("java.security.krb5.conf", krb5Location);
    }

    //模拟curl使用kerberos认证
    private  HttpClient buildSpengoHttpClient() {
        HttpClientBuilder builder = HttpClientBuilder.create();
        Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().
                register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
        builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
            @Override
            public Principal getUserPrincipal() {
                return null;
            }

            @Override
            public String getPassword() {
                return null;
            }
        });
        builder.setDefaultCredentialsProvider(credentialsProvider);
        CloseableHttpClient httpClient = builder.build();
        return httpClient;
    }

    public  String doPut(String url, Map<?, ?> json) {
        String formatJson = JSONUtils.toJson(json);
        return doPut(url, formatJson);
    }

    public String doPut(String url, String json) {
        logger.warn(String.format("Calling KerberosHttpClient %s %s %s", this.principal, this.keyTabLocation, url));
        Configuration config =getConfig();
        Subject sub = getSubject();
        StringEntity stringEntity = new StringEntity(json.toString(), ContentType.APPLICATION_JSON);
        stringEntity.setContentEncoding("utf-8");
        try {
            //认证模块：Krb5Login
            LoginContext lc = new LoginContext("Krb5Login", sub, null, config);
            lc.login();
            Subject serviceSubject = lc.getSubject();
            return Subject.doAs(serviceSubject, new PrivilegedAction<String>() {

                @Override
                public String run() {
                    try {
                        HttpPut httpPost = new HttpPut(url);
                        httpPost.setEntity(stringEntity);

                        httpPost.addHeader("Content-Type", "application/json");

                        HttpClient spnegoHttpClient = buildSpengoHttpClient();
                        HttpResponse httpResponse = spnegoHttpClient.execute(httpPost);

                        return EntityUtils.toString(httpResponse.getEntity(),"utf-8");
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                    return "";
                }
            });
        } catch (Exception le) {
            le.printStackTrace();
        }
        return "";
    }

    public  String doPost(String url, Map<?, ?> json) {
        String formatJson = JSONUtils.toJson(json);
        return doPost(url, formatJson);
    }

    /**
     * "post" request to transfer "json" data
     *
     * @param url
     * @param json
     * @return
     */
    public String doPost(String url, String json) {
        logger.warn(String.format("Calling KerberosHttpClient %s %s %s", this.principal, this.keyTabLocation, url));
        Configuration config =getConfig();
        Subject sub = getSubject();
        StringEntity stringEntity = new StringEntity(json.toString(), ContentType.APPLICATION_JSON);
        stringEntity.setContentEncoding("utf-8");
        try {
            //认证模块：Krb5Login
            LoginContext lc = new LoginContext("Krb5Login", sub, null, config);
            lc.login();
            Subject serviceSubject = lc.getSubject();
            return Subject.doAs(serviceSubject, new PrivilegedAction<String>() {

                @Override
                public String run() {
                    try {
                        HttpPost httpPost = new HttpPost(url);
                        httpPost.setEntity(stringEntity);
                        httpPost.addHeader("Content-Type", "application/json");

                        HttpClient spnegoHttpClient = buildSpengoHttpClient();
                        HttpResponse httpResponse = spnegoHttpClient.execute(httpPost);

                        return EntityUtils.toString(httpResponse.getEntity(),"utf-8");
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                    return "";
                }
            });
        } catch (Exception le) {
            le.printStackTrace();
        }
        return "";
    }

    private Configuration getConfig(){
        Configuration config = new Configuration() {
            @SuppressWarnings("serial")
            @Override
            public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
                return new AppConfigurationEntry[]{new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
                        AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap<String, Object>() {
                    {
                        put("useTicketCache", "false");
                        put("useKeyTab", "true");
                        put("keyTab", keyTabLocation);
                        //Krb5 in GSS API needs to be refreshed so it does not throw the error
                        //Specified version of key is not available
                        put("refreshKrb5Config", "true");
                        put("principal", principal);
                        put("storeKey", "true");
                        put("doNotPrompt", "true");
                        put("isInitiator", "true");
                        put("debug", "true");
                    }
                })};
            }
        };
        return config;
    }

    private Subject getSubject(){
        Set<Principal> princ = new HashSet<Principal>(1);
        princ.add(new KerberosPrincipal(this.principal));
        Subject sub = new Subject(false, princ, new HashSet<Object>(), new HashSet<Object>());
        return sub;
    }


    public String get(final String url) {
        logger.warn(String.format("Calling KerberosHttpClient %s %s %s", this.principal, this.keyTabLocation, url));
        Configuration config =getConfig();
        Subject sub = getSubject();
        try {
            //认证模块：Krb5Login
            LoginContext lc = new LoginContext("Krb5Login", sub, null, config);
            lc.login();
            Subject serviceSubject = lc.getSubject();
            return Subject.doAs(serviceSubject, new PrivilegedAction<String>() {

                @Override
                public String run() {
                    try {
                        HttpUriRequest request = new HttpGet(url);

                        HttpClient spnegoHttpClient = buildSpengoHttpClient();
                        HttpResponse httpResponse = spnegoHttpClient.execute(request);

                        return EntityUtils.toString(httpResponse.getEntity(),"utf-8");
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                    return "";
                }
            });
        } catch (Exception le) {
            le.printStackTrace();
        }
        return "";
    }

    public HttpResponse callRestUrl(final String url) {
        logger.warn(String.format("Calling KerberosHttpClient %s %s %s", this.principal, this.keyTabLocation, url));
        Configuration config = new Configuration() {
            @SuppressWarnings("serial")
            @Override
            public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
                return new AppConfigurationEntry[]{new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
                        AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap<String, Object>() {
                    {
                        put("useTicketCache", "false");
                        put("useKeyTab", "true");
                        put("keyTab", keyTabLocation);
                        //Krb5 in GSS API needs to be refreshed so it does not throw the error
                        //Specified version of key is not available
                        put("refreshKrb5Config", "true");
                        put("principal", principal);
                        put("storeKey", "true");
                        put("doNotPrompt", "true");
                        put("isInitiator", "true");
                        put("debug", "true");
                    }
                })};
            }
        };
        Set<Principal> princ = new HashSet<Principal>(1);
        princ.add(new KerberosPrincipal(this.principal));
        Subject sub = new Subject(false, princ, new HashSet<Object>(), new HashSet<Object>());
        try {
            //认证模块：Krb5Login
            LoginContext lc = new LoginContext("Krb5Login", sub, null, config);
            lc.login();
            Subject serviceSubject = lc.getSubject();
            return Subject.doAs(serviceSubject, new PrivilegedAction<HttpResponse>() {
                HttpResponse httpResponse = null;

                @Override
                public HttpResponse run() {
                    try {
                        HttpUriRequest request = new HttpGet(url);

                        HttpClient spnegoHttpClient = buildSpengoHttpClient();
                        httpResponse = spnegoHttpClient.execute(request);
                        return httpResponse;
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                    return httpResponse;
                }
            });
        } catch (Exception le) {
            le.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String user ="hive/pt182@HADOOP.COM";
        String keytab="D:\\tmp\\bjhdp\\182\\hive.service.keytab";
        String krb5Location="D:\\tmp\\bjhdp\\krb5.conf";

        try{
            HttpKerberosUtils restTest = new HttpKerberosUtils(user,keytab,krb5Location, false);

            // refer to https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/WebHDFS.html#Open_and_Read_a_File
            // list dir
            String url_liststatus="http://pt181:50070/webhdfs/v1/bdp?op=liststatus";
            // location
            String url_get_block_locations="http://pt181:50070/webhdfs/v1/bdp/402880a476b21f6d0176b6ec4b45003e?op=get_block_locations";

            String url = "http://pt182:8088/ws/v1/cluster/apps/application_1629682142111_0022/state";
            //String url = "http://118.113.164.51:23680/ws/v1/cluster/apps";

            Map<String,String> map = new HashMap<>();
            map.put("state", "KILLED");

            String str = restTest.doPut(url,map);
           System.out.println(str);
          //HttpResponse response = restTest.callRestUrl(url_get_block_locations,user);


//            InputStream is = response.getEntity().getContent();
//            System.out.println("Status code " + response.getStatusLine().getStatusCode());
//            System.out.println("message is :"+ Arrays.deepToString(response.getAllHeaders()));
//            System.out.println("string：\n"+new String(IOUtils.toByteArray(is), "UTF-8"));

        }catch (Exception exp){
            exp.printStackTrace();
        }

    }

}
